package com.tutor.lzm.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.InputType;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.cfg.PackageVersion;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.tutor.lzm.AppSession;
import com.tutor.lzm.R;
import com.tutor.lzm.SplashActivity;
import com.tutor.lzm.app.CommonValue;
import com.tutor.lzm.app.Constant;
import com.tutor.lzm.bean.UserInfo;
import com.tutor.lzm.http.BaseResponse;
import com.tutor.lzm.http.HttpClient;
import com.tutor.lzm.http.UserInfoResponse;
import com.tutor.lzm.http.request.UserInfoRequest;
import com.tutor.lzm.http.request.UserLoginRequest;
import com.tutor.lzm.utils.SPKey;
import com.tutor.syslib.Logs;
import com.tutor.syslib.util.AndroidUtils;
import com.tutor.syslib.util.AnimUtils;
import com.tutor.syslib.util.JsonParse;
import com.tutor.syslib.util.MessageTools;
import com.tutor.syslib.util.TextUtil;
import com.tutor.syslib.view.EditTextWithDelete;

import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HTTP;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by zzgpc on 2017-9-10.
 * 登录
 */
public class LoginActivity extends BaseActivity {

    private String tag = "LoginActivity";
    private boolean ishide = true;

    @BindView(R.id.username)
    EditTextWithDelete etusername;
    @BindView(R.id.password)
    EditTextWithDelete etpassword;
    @BindView(R.id.im_eye)
    ImageView imEye;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        TextView titleTv = (TextView) findViewById(R.id.title_txt);
        titleTv.setText("登录");

        String phone = AppSession.getAppSPDataNoId(SPKey.phone);
        String psd = AppSession.getAppSPDataNoId(SPKey.password);

        etusername.setText(phone);
        etpassword.setText(psd);

    }

    @Override
    protected void onResume() {
        super.onResume();
//        String mobil = appSession.getMobile();
//        etusername.setText(mobil);
//        etpassword.setText(PreferencesUtils.getString(oThis, "dlmm", "").toString().trim());
    }


    // 登录
    private void login() {
        int ecolor = Color.RED; // whatever color you want
        ForegroundColorSpan fgcspan = new ForegroundColorSpan(ecolor);
        final String phone = etusername.getText().toString().trim();
        final String psd = etpassword.getText().toString().trim();
        if (TextUtil.isNull(phone)) {
            String estring = "手机号码不能为空！";
            SpannableStringBuilder ssbuilder = new SpannableStringBuilder(estring);
            ssbuilder.setSpan(fgcspan, 0, estring.length(), 0);
            etusername.setError(ssbuilder);
            return;
        }
        if (!TextUtil.isMobile(phone)) {
            String estring = "请输入正确的手机号";
            SpannableStringBuilder ssbuilder = new SpannableStringBuilder(estring);
            ssbuilder.setSpan(fgcspan, 0, estring.length(), 0);
            etusername.setError(ssbuilder);
            return;
        }
        if (TextUtil.isNull(psd)) {
            String estring = "请输入密码";
            SpannableStringBuilder ssbuilder = new SpannableStringBuilder(estring);
            ssbuilder.setSpan(fgcspan, 0, estring.length(), 0);
            etpassword.setError(ssbuilder);
            return;
        }
        final String psdMD5 = TextUtil.stringToMD5(psd);


        {
            // TODO Auto-generated method stub
            // begin to login
            RequestParams params = new RequestParams();

            try {

                UserLoginRequest request = new UserLoginRequest();
                request.setUid(phone);
                request.setRid("mobile");
                request.setPwd(psdMD5);
                request.setforAccessToken(true);
                ObjectMapper mapper = new ObjectMapper();
                String json = mapper.writeValueAsString(request);
                params.setBodyEntity(new StringEntity(json, "UTF-8"));
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            // send request

            HttpUtils http = new HttpUtils();
            params.addHeader("Content-Type", "application/json");
            params.addHeader("charset", HTTP.UTF_8);
            http.send(HttpRequest.HttpMethod.POST, CommonValue.BASE_HOST_LOGIN, params,

                    new RequestCallBack<String>() {

                        @Override
                        public void onStart() {
                            Logs.d(tag, "conn...  login  start");
                            showMyDialog(getString(R.string.logining));
                        }

                        @Override
                        public void onLoading(long total, long current, boolean isUploading) {

                        }

                        @Override
                        public void onSuccess(ResponseInfo<String> responseInfo) {
                            Logs.d(tag, "Receive response:" + responseInfo.result);


//                            if (AppSession.tokenId != null) {
                            //如果登录成功了，则做一些初始化工作
                            //如果登录成功了，则做一些初始化工作
                            int code = 0;
                            String result = responseInfo.result;
                            UserInfoResponse resp = null;
                            resp = new Gson().fromJson(result, UserInfoResponse.class);
                            code = resp.getCode();
                            if (result.indexOf("\"body\":") != -1) {
                                // Success
                                resp = JsonParse.getInstance().getObjectFromJson(result, UserInfoResponse.class);
//                                    AppSession.mCurrentPatient = resp.getBody().getProperties().patient;
//                                    AppSession.mpid = AppSession.mCurrentPatient.getMpiId();

//                                    AppSession.saveAppSessionData("patient", AppSession.mCurrentPatient);
//                                    AppSession.saveAppSessionData("patientId", AppSession.mpid);
                            }

//                                UMAnalyticsManager.onEvent(activity, UMAnalyticsManager.UM_EVENT_NRD_Login_success);
//
//                                Intent mIntent = new Intent(PatientApplication.getInstance(), DataInitService.class);
//                                mIntent.putExtra("action", DataInitService.ACTION_INIT_AFTERLOGIN);
//                                PatientApplication.getInstance().startService(mIntent);
//                            }

                            // Success
                            if (code == 200) {
//                                AppSession.getInstance().setLoginUserInfo(resp);
                                AppSession.tokenId = resp.getProperties().accessToken;
                                AppSession.saveAppSessionDataNoId("tokenId", AppSession.tokenId);
                                AppSession.saveAppSessionDataNoId(SPKey.phone, phone);
                                String userID = resp.getBody().id;
                                AppSession.getInstance().setUserId(userID);
                                AppSession.saveAppSessionDataNoId(SPKey.password, psd);
                                getUserInfo(userID);

                            } else {

                                MessageTools.showToast(getApplicationContext(), resp.getMessage());

                                closeDialog();
                            }

                        }

                        @Override
                        public void onFailure(HttpException error, String msg) {
                            Logs.d(tag, "onFailure:" + error.getExceptionCode() + " msg :"
                                    + msg);
                            MessageTools.showToast(getApplicationContext(), msg);
                            closeDialog();
                        }
                    });

        }

    }


    /**
     * 获取个人信息
     *
     * @param id
     */
    private void getUserInfo(String id) {
        UserInfoRequest request = new UserInfoRequest();
        request.setUserId(id);
        HttpClient.post(request, new HttpClient.onSuccessListener() {
            @Override
            public void onSuccess(BaseResponse response) {
                UserInfo info = (UserInfo) response;
                AppSession.getInstance().setUserId(info.userId);
                AppSession.getInstance().setUserInfo(info);
                if (info.status == 1) {
                    AppSession.getInstance().setIsTeacher(false);
                } else {
                    AppSession.getInstance().setIsTeacher(true);
                }
                MainActivity.startActivity(LoginActivity.this);
                finish();
                closeDialog();
            }
        }, new HttpClient.onFailListener() {
            @Override
            public void onFail(int code, String msg) {
                MessageTools.showToast(getApplicationContext(), msg);
                closeDialog();

            }
        });
    }


    /**
     * 密码隐藏显示
     */
    public void eyeClick() {
        if (!ishide) {
            imEye.setImageResource(R.mipmap.eyes_close);
            etpassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            ishide = true;
        } else {
            imEye.setImageResource(R.mipmap.eyes_open);
            etpassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
            ishide = false;
        }
        etpassword.setSelection(etpassword.length());
    }

    @OnClick({R.id.im_eye, R.id.login_button, R.id.login_register, R.id.findpw})
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.im_eye:
                //密码隐藏显示
                eyeClick();
                break;
            case R.id.login_button:
                AndroidUtils.closeKeyboard(getApplicationContext(), etpassword);
                login();
//                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                break;
            case R.id.login_register:
                intent = new Intent(oThis, RegisterActivity.class);
                startActivity(intent);
                AnimUtils.inRightOutleft(oThis);
                break;
            case R.id.findpw:
                //忘记密码
//                intent = new Intent(oThis, FindpasswordActivity.class);
//                intent = new Intent(oThis, EvaluationActivity.class);
//                intent.putExtra("firstAdd", true);
//                startActivity(intent);
//                AnimUtils.inRightOutleft(oThis);
                break;
        }
    }

}
